<?php

class DB
{
	
	private $dsn ;
	private $user ;
	private $pass ;
	private $pdo ;
	private $pdoStatement ;
	private static $instance ;
	
	public static function &getInstance ( $config )
	{
		if ( ! isset ( self::$instance ) )
		{
			self::$instance = new DB ( $config ) ;
		}
		return self::$instance;
	}
	
	public function __construct ( $config )
	{
		$this->dsn = $config['dsn'] ;
		$this->user = $config['user'] ;
		$this->pass = $config['pass'] ;
		self::$instance = $this ;
	}
	
	public function __destruct ( )
	{
		
		$this->pdoStatement = null ;
		$this->pdo = null ;
		
	}
	
	public function connect ( )
	{
		$this->pdo = new PDO ( $this->dsn, $this->user, $this->pass, array ( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" ) ) ;
	}
	
	public function disconnect ( )
	{
		$this->pdo = null ;
	}
	
	public function query ( $query, $params = array ( ) )
	{
		if ( $this->pdo === null )
		{
			$this->connect ( ) ;
		}
		
		$this->pdoStatement = $this->pdo->prepare ( $query ) ;
		$this->pdoStatement->setFetchMode ( PDO::FETCH_ASSOC ) ;
		
		foreach ( $params as $key => $param )
		{
			$this->pdoStatement->bindParam ( $key, $param['value'], $param['type'] ) ;
		}
		
		$this->pdoStatement->execute ( ) ;
	}
	
	public function lastId ( )
	{
		return $this->pdo->lastInsertId ( ) ;
	}
	
	public function fetchAll ( )
	{
		return $this->pdoStatement->fetchAll ( ) ;
	}
	
}

?>